package com.bee.beemanage.system.common.utils.transaction;

import cn.hutool.extra.spring.SpringUtil;
import com.bee.beemanage.system.common.utils.exceptions.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.support.DefaultTransactionDefinition;

public class TransUtils {
    private static final Logger logger = LoggerFactory.getLogger(ExceptionUtils.class);
    private static DefaultTransactionDefinition txDefinition;
    static {
        txDefinition = new DefaultTransactionDefinition();
        txDefinition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    }

    public static Transaction getTrans() {
        Transaction ut = new MyTransaction();
        PlatformTransactionManager transactionManager = SpringUtil.getBean(PlatformTransactionManager.class);

        ut.setTxManager(transactionManager);
        ut.setTransactionDefinition(txDefinition);
        return ut;
    }

    public static void commit(Transaction trans) {
        if(null != trans) {
            try {
                trans.commit();
            } catch (Exception e) {
                logger.error("事务提交失败");
            }
        }
    }

    public static void rollback(Transaction trans) {
        if(null != trans) {
            try {
                trans.rollback();
            } catch (Exception e) {
                logger.error("事务回滚失败");
            }
        }
    }
}
